/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pfc.generacion;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;

/**
 *
 * @author xandru
 */
public class HTMLPrinter {

    PrintWriter _out;
    public HTMLPrinter(String fichero) throws FileNotFoundException
    {
        _out = new PrintWriter(fichero);
    }

    public void print(HTMLDocument doc) {
        HTMLTag root = doc.getHTMLRoot();

        printJspImports(doc.getJspImports());
        printTag(root);
        _out.flush();
        _out.close();
    }

    public void printTag(HTMLTag t)
    {
        _out.print("<" + t._tag);
        Properties p = t.getAttributes();
        for (Enumeration e = p.keys();e.hasMoreElements();)
        {
            String key = (String)e.nextElement();
            String value = p.getProperty(key);
            _out.print(" " + key + "=\"" + value + "\"");
        }



        _out.println(">");

        if (!t.getJspCode().isEmpty())
        {
            _out.println("<%");

            for (String s: t.getJspCode())
                _out.println(s);

            _out.println("%>");
        }
        /*
        boolean cerrado=false;
        if (!t.hasChildren())
        {
            _out.println("/>");
            cerrado = true;
        }
        else {
            _out.println(">");
        }
*/
        for (HTMLTag t1:t.getChildrens())            
               printTag( t1);

        for (String s : t.getText()) 
                _out.println( s ) ;

  //      if (!cerrado)
            _out.println("</" + t.getTag() + ">");
                
    }

    private void printJspImports(Iterable<String> imports) {
        for (String s: imports)
        {
            _out.println(s);
        }
    }

    


}
